import { exportVoteProcess, exportVoteRank, listVoteProcess, rankVoteResult, rankVoteResultAnalysis } from '@/services/api/api-assess-week-emphasize-vote';
import { ActionType, DrawerForm, ProCard, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Descriptions, Divider, Flex, message, Radio, Space, Switch, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useEffect, useRef, useState } from 'react';
import DetailRecord from '../record/DetailRecord';
import access from '@/access';
import { useAccess } from '@umijs/max';
dayjs.extend(customParseFormat);

interface TableVoteResultProps {
  range: AssessWeekEmphasizeVoteData.RangePage | undefined;
  onRevote(): void;
}

const TableVoteResult: React.FC<TableVoteResultProps> = ({ range, onRevote }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [dataReportType, setDataReportTypeState] = useState<React.Key>('1');
  const [datahubLevel, setDatahubLevelState] = useState<React.Key>('2000');
  const [analysis, setAnalysisState] = useState<AssessWeekEmphasizeVoteData.Analysis>();


  const [isMine, setIsMineState] = useState<number>(access.传播质效x投票x配置x管理员 ? 0 : range?.state);

  const columns: ProColumns<AssessWeekEmphasizeVoteData.ResultRank>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >

        </span>
      ),
      dataIndex: 'voteCount',
      // valueType: 'indexBorder',
      width: 48,
      align: 'center',
      render: (dom, entity, index, action) => {
        return (
          entity.isMineVote == 1 ? <Tag color="#faad14">我</Tag> : <></>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          票数
        </span>
      ),
      dataIndex: 'voteCount',
      // valueType: 'indexBorder',
      width: 48,
      align: 'center',
      render: (dom, entity, index, action) => {
        return (
          access.传播质效x投票x配置x管理员 ?
            <DrawerForm
              title="投票人员名单"
              trigger={
                <a> {entity.voteCount} </a>
              }
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
                width: 400,
              }}
              submitter={false}
            >
              <ProTable<AssessWeekEmphasizeVoteData.AssessEmphasizeVoteProcessListItem>
                columns={[
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        姓名
                      </span>
                    ),
                    dataIndex: 'createdAccountName',
                    align: 'center',
                    ellipsis: true,
                    width: '30%',
                  },
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        投票时间
                      </span>
                    ),
                    dataIndex: 'createdTime',
                    align: 'center',
                    width: '100px',
                  },
                ]}
                request={async (params = {}, sorter) => {
                  const response = await listVoteProcess({
                    ...params,
                    rangeId: range?.id,
                    recordId: entity.id,
                  });
                  return {
                    data: response.data,
                    success: true,
                    total: response.data?.length,
                  };
                }}
                actionRef={actionRef}
                defaultSize={'small'}
                pagination={false}
                search={false}
                options={{
                  density: false,
                  setting: false,
                  reload: false,
                }}
                ghost
              />
            </DrawerForm> : entity.voteCount
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          {datahubLevel == '2000' ? '媒体单位' : '区域'}
        </span>
      ),
      dataIndex: 'areaName',
      align: 'center',
      width: '150px',
      render: (dom, entity, index, action) => {
        if (datahubLevel == '2000') {
          return (
            <span
              style={{
                color: '',
              }}
            >
              {entity.appointSourceOrganizationNames.map((item) => item)}
            </span>
          );
        } else {
          return (
            <span
              style={{
                color: '',
              }}
            >
              {entity.areaName}
            </span>
          );
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'dataName',
      align: 'center',
      ellipsis: true,
      copyable: true,
      width: '60%',
      render: (dom, entity, index, action) => (
        <div
          style={{
            textAlign: 'left',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }}
        >
          <DetailRecord
            entrance="vote"
            id={entity.id}
            name={entity.dataName}
            onRefurbish={function (): void {
              actionRef.current?.reloadAndRest();
            }}
            onExhibitionRefurbish={function (): void {
              actionRef.current?.reloadAndRest();
            }}
          />
        </div>
      ),
    },
  ];

  const loadAankVoteResultAnalysis = async () => {
    const response = await rankVoteResultAnalysis({
      voteRangeId: range?.id,
    });

    if (response.code === 0) {
      const data = response.data;
      setAnalysisState(data);
    }
  };

  useEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [range]);

  return (
    <>
      <ProCard
        ghost
        title={
          <span
            style={{
              fontSize: '16px',
              color: '#000000e0',
              fontWeight: '600',
            }}
          >{`投票结果汇总信息：${range?.name}`}</span>
        }
        extra={
          range?.state == 1 ? (
            <Button
              type="primary"
              danger
              onClick={() => {
                onRevote();
              }}
            >
              重新投票
            </Button>
          ) : <Button onClick={async () => {

            const response = await exportVoteRank({ voteRangeId: range?.id });
            if (response.code === 0) {
              message.success('导出成功');
            }

          }}>导出结果</Button>
        }
        loading={analysis == undefined}
      >
        {(range?.state == 0 || access.传播质效x投票x配置x管理员) && <Descriptions size="small" column={3}>
          <Descriptions.Item label="参与投票人数">
            <DrawerForm
              title="投票人员名单"
              trigger={
                <a>{`${analysis?.participateCombineCount} / ${analysis?.assignCombineCount}`}</a>
              }
              autoFocusFirstInput
              drawerProps={{
                destroyOnClose: true,
                width: 600,
              }}
              submitter={false}
            >
              <ProTable<AssessWeekEmphasizeVoteData.AssignCombine>
                columns={[
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        姓名
                      </span>
                    ),
                    dataIndex: 'dataName',
                    align: 'center',
                    ellipsis: true,
                    copyable: true,
                    width: '18%',
                    render: (dom, entity, index, action) => (
                      <div style={{ color: entity.isParticipate == 1 ? '' : 'red' }}>
                        {entity.accountName}
                      </div>
                    ),
                  },
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        投票数
                      </span>
                    ),
                    dataIndex: 'recordCount',
                    align: 'center',
                    width: '50px',
                  },
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        投票时间
                      </span>
                    ),
                    dataIndex: 'createdTime',
                    align: 'center',
                    width: '150px',
                  },
                  {
                    title: (
                      <span
                        style={{
                          color: '#99a3b7',
                          fontSize: 12,
                          textAlign: 'center',
                          fontWeight: 'normal',
                        }}
                      >
                        操作
                      </span>
                    ),
                    valueType: 'option',
                    width: '80px',
                    fixed: 'right',
                    render: (_, row, index, action) => [
                      <a
                        key="a_export_vote_process"
                        onClick={async () => {
                          const response = await exportVoteProcess({ voteRangeId: range?.id, createdCombineId: row.assignCombineId });
                          if (response.code === 0) {
                            message.success('导出成功');
                          }
                        }}
                      >
                        确认投票导出
                      </a>,
                    ],
                  },
                ]}
                actionRef={actionRef}
                rowKey="assignCombineId"
                dateFormatter="assignCombineId"
                defaultSize={'small'}
                pagination={false}
                search={false}
                dataSource={analysis?.assignCombines}
                options={{
                  density: false,
                  setting: false,
                  reload: false,
                }}
                ghost
              />
            </DrawerForm>
          </Descriptions.Item>
          <Descriptions.Item label="总投票计数">{`${analysis?.recordCount}`}</Descriptions.Item>
        </Descriptions>}
      </ProCard>
      <Divider />
      <Flex justify={'space-between'} align={'center'}>
        <Space align="end">
          <span
            style={{
              fontWeight: '600',
              fontSize: '16px',
              color: '#000000e0',
            }}
          >
            投票榜单
          </span>
          <span
            style={{
              fontSize: '14px',
              color: '#00000073',
              fontWeight: 'normal',
            }}
          >
            当投票结束后会展示所有投票结果
          </span>
        </Space>
        <Switch defaultChecked={isMine == 1} disabled={
          access.传播质效x投票x配置x管理员 ? false : range?.state == 1
        }
          checkedChildren="只看自己" unCheckedChildren="全部" onChange={checked => {
            setIsMineState(checked ? 1 : 0)
            actionRef.current?.reloadAndRest()
          }} />
      </Flex>


      <ProTable<AssessWeekEmphasizeVoteData.ResultRank>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        request={async (params = {}, sorter) => {
          const response = await rankVoteResult({
            ...params,
            voteRangeId: range?.id,
            dataReportTypes: [dataReportType],
            datahubLevelIds: [datahubLevel],
            isMine: isMine,
          });
          loadAankVoteResultAnalysis();
          return {
            data: response.data,
            success: true,
            total: response.data?.length,
          };
        }}
        dateFormatter="id"
        defaultSize={'small'}
        pagination={false}
        search={false}
        options={{
          density: false,
          setting: false,
        }}
        ghost
        scroll={{
          x: '625px',
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: dataReportType,
            items: [
              {
                key: '1',
                label: <span>好报道</span>,
              },
              {
                key: '2',
                label: <span>好评论</span>,
              },
              {
                key: '3',
                label: <span>好创意报道</span>,
              },
            ],
            onChange: (key) => {
              setDataReportTypeState(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
          filter: (
            <Space>
              <Radio.Group
                defaultValue={'2000'}
                optionType="button"
                buttonStyle="solid"
                size="middle"
                onChange={(e) => {
                  setDatahubLevelState(e.target.value);
                  actionRef.current?.reloadAndRest();
                }}
              >
                <Radio.Button value="2000">市属媒体</Radio.Button>
                <Radio.Button value="3000">区县媒体</Radio.Button>
              </Radio.Group>
            </Space>
          ),
        }}
      />
    </>
  );
};
export default TableVoteResult;
